import { defineStore } from "pinia"
import type { useUserStorageModel } from "@/common/type/UserModel"

export const useUserStore = defineStore("useUserStore", {
	state: (): useUserStorageModel => ({
		userId: null,
		username: null,
		token: null,
	}),
	getters: {
		getUserId(state): string | null {
			return state.userId
		},
		getUsername(state): string | null {
			return state.username
		},
		getToken(state): string | null {
			return state.token
		},
		getUserInfo(state): useUserStorageModel {
			return {
				userId: state.userId,
				username: state.username,
				token: state.token,
			}
		},
	},
	actions: {
		setUserId(userId: string | null) {
			this.userId = userId
		},
		setUsername(username: string | null) {
			this.username = username
		},
		setToken(token: string | null) {
			this.token = token
		},
		setUserInfo(userInfo: Partial<useUserStorageModel>) {
			this.userId = userInfo.userId ?? this.userId
			this.username = userInfo.username ?? this.username
			this.token = userInfo.token ?? this.token
		},
		clearUserInfo() {
			this.userId = null
			this.username = null
			this.token = null
		},
	},
	persist: {
		key: "userStore",
		storage: localStorage,
		pick: ["userId", "username"],
	},
})
